import {
    reqgetbanner,
    reqgetcate
} from "../../http/api"
// 初始值
const initState = {
    cates: [],
    banner: [],
}

const types = {
    change_cate: "home_change_cate",
    change_banner: "home_change_banner"
}

//reducer 
const reducer = (state = initState, action) => {
    switch (action.type) {
        case types.change_cate:
            return {
                ...state,
                cates: action.cates
            }
            break
        case types.change_banner:
            return {
                ...state,
                banner: action.banner
            }
            break
        default:
            return state;
    }
}

//actionCreators
export const actions = {
    changeCate: cates => ({
        type: types.change_cate,
        cates
    }),
    reqCate: () => (disaptch, getState) => {
        if(getState().home.cates.length>0){
            return;
        }
        reqgetcate().then(res => {
            //修改cate 
            disaptch(actions.changeCate(res.data.list))
        })
    },
    changeBanner:banner=>({type:types.change_banner,banner}),
    reqBanner:()=>(dispatch,getState)=>{
        if(getState().home.banner.length>0){
            return;
        }
        reqgetbanner().then(res=>{
            dispatch(actions.changeBanner(res.data.list))
        })
    },
}

//selector
export const getCates = state => state.home.cates;
export const getBanner=state=>state.home.banner;

export default reducer